package com.deyuanyun.pic.pig.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.caixu.beanvalidateutil.imlclass.BeanValidateUtil;
import com.caixu.beanvalidateutil.imlclass.VResult;
import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.tool.ExceplImportCheck;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.MyCollectionUtil;
import com.deyuanyun.pic.common.util.NumberUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.ResponseUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.poi.WriteExcel;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.pig.domain.CleanPipeLineManagerVo;
import com.deyuanyun.pic.pig.domain.PigTask;
import com.deyuanyun.pic.pig.domain.PigTaskPoint;
import com.deyuanyun.pic.pig.domain.TrackPointExportVO;
import com.deyuanyun.pic.pig.domain.TrackPointImportVO;
import com.deyuanyun.pic.pig.mapper.PigTaskMapper;
import com.deyuanyun.pic.pig.service.CleanPipeLineManagerService;
import com.deyuanyun.pic.pig.service.CleanPipeLineTrackService;
import com.deyuanyun.pic.service.pipe.PipeLineService;
import com.deyuanyun.pic.support.biz.CodeUtil;

import jxl.read.biff.BiffException;
@Controller
@RequestMapping("/cleanTask/cleanPipeLineTrack")
public class CleanPipeLineTrackController extends PiggingBaseController {
	
	@Resource
	private CleanPipeLineTrackService cleanPipeLineTrackService;
	@Resource
	private CleanPipeLineManagerService cleanPipeLineManagerService;
	
	@Resource(name="pipeLineServiceImpl")
	private PipeLineService pipeLineService;
	
	/**
	 * 跳转任务追踪主页
	 * 
	 * @return
	 */
	@RequestMapping("/getCleanPipeLineTrackIndex.html")
	public ModelAndView getCleanPipeLineTrackIndex() {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("pipeLine", pipeLineService.getLine());
		map.put("sCode", CodeUtil.getCodeList("PIGGING_TYPE"));
		return forword("/pig/cleanPipeLineTrack", map);
	}

	/**
	 * 加载追踪列表数据
	 * @param vo
	 */
	@RequestMapping("/getDataList.json")
	@ResponseBody
	public void getDataList(CleanPipeLineManagerVo vo){
		PageJsonBean jsonBean = new PageJsonBean();
		List list = cleanPipeLineTrackService.getCleanPipeLineTrackIndex(vo);
		jsonBean.setList(list);
		AjaxSupport.sendSuccessText("", jsonBean);
	}
	
	/**
	 * 任务追踪
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/trackFun.json")
	@ResponseBody
	public void trackFun(String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "获取任务数据异常，请刷新页面后重试");
		List<PigTaskPoint> list = cleanPipeLineTrackService.getInspTaskPointByTaskId(taskId);
		AjaxSupport.sendSuccessText("", list);
	}
	
	/**
	 * 任务监控
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/monitorFun.html")
	public ModelAndView monitorFun(String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "没有获取到对应的任务数据");
		Map<String,Object> map = new HashMap<String,Object>();
		map = cleanPipeLineTrackService.getInspMonitorByTaskId(taskId,map);
		map.put("taskId", taskId);
		return forword("/pig/monitor", map);
	}
	
	
	@RequestMapping("/getMonito")
	public void getMonito(@RequestParam HashMap param,HttpServletResponse response){
		List list=cleanPipeLineTrackService.getMonito(param);
		ResponseUtil.printl(response, ResponseUtil.getJson(list).toString(), "json");
	}
	
	/**
	 * 导出跟踪点
	 * @param response
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/exportTrackPoint.json")
	@ResponseBody
	public void exportTrackPoint(HttpServletResponse response,String taskId)throws Exception{

		String templateName = "out/trackPoint_out_template.xls";
		String fileName = "跟踪点";
		Workbook workbook = ReadExcel.readExcelTemplate(templateName);
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		List<TrackPointExportVO> list = cleanPipeLineTrackService.excelExport(taskId);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (TrackPointExportVO trackPointExport : list) {
			if(trackPointExport.getMileage() != null) {
				String mileage = NumberUtil.toBigDecimal(BigDecimal.valueOf(Double.valueOf(trackPointExport.getMileage())), 3).toString();
				trackPointExport.setMileage(mileage);
			}
			if(trackPointExport.getPassTime() != null) {
				String passTime = df.format(Timestamp.valueOf(trackPointExport.getPassTime()));
				trackPointExport.setPassTime(passTime);
			}
		}
		Workbook workbookFinal = WriteExcel.writeExcel(workbook, list, 1, null);
			//隐藏跟踪点id列
        /*Sheet sh = workbookFinal.getSheetAt(0);
        sh.setColumnHidden(0, true);
        sh.setColumnHidden(1, true);*/
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			workbookFinal.write(outputStream);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
		return;
	}
	/**
	 * 导入跟踪点
	 * @param response
	 * @param taskId
	 * @return
	 * @throws IOException 
	 * @throws BiffException 
	 */
	@RequestMapping("/importTrackPoint.json")
	@ResponseBody
	public void importTrackPoint(@RequestParam("file")MultipartFile[] multipartFiles,HttpServletResponse response,String taskId) throws Exception{
		Asserts.assertTrue(!ObjectUtil.isEmptyAll(multipartFiles),"附件不能为空");
		List<TrackPointImportVO> xx= ReadExcel.readExcle(TrackPointImportVO.class,multipartFiles[0].getInputStream(),1,"9");
		List<TrackPointImportVO> finalInfo= MyCollectionUtil.removeLastEmpty(xx);
		VResult b= BeanValidateUtil.vali2(finalInfo,1+"");
		if (b.isRelult()){
			int count = cleanPipeLineTrackService.importTrackPoint(finalInfo,taskId);
			if(count > 0){
				AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);
			}else{
				response.setStatus(503);
				AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage("失败，没有成功导入跟踪点"));
			}
        }else {
			String[] titleArr= ReadExcel.getTitle(multipartFiles[0],"in/trackPoint_t.xls");
            String m=b.getAllString(titleArr);
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage(m));
        }
        return;
	}
	
	/**
	 * 上传进度
	 * @param clientId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/uploadProgress.json")
	public void uploadProgress(String clientId, HttpServletRequest request, HttpServletResponse response) throws Exception{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/text");
		response.getWriter().write(ExceplImportCheck.getProgress(clientId));
	}
	
	
	/**
	 * 保存跟踪信息
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/saveTaskTrack.json")
	@ResponseBody
	public void saveTaskTrack(String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "获取任务数据异常，请刷新页面后重试");
		Map<String,Object> map =new HashMap<String,Object>();
		int a = cleanPipeLineTrackService.saveTaskTrack(taskId);
		if(a > 0){
			map.put("msgCode", "ok");
		}
		AjaxSupport.sendSuccessText("", map);
	}
	
	
	@RequestMapping("/getMonitorGisJson")
	public void getMonitorGisJson(@RequestParam HashMap param,HttpServletResponse response){
		ResponseUtil.printl(response, cleanPipeLineTrackService.getMonitoGisPoint(param), "json");
	}
	/**
	 * 根据收发球的编号查询收发球
	 * @param pigNum
	 * @return
	 */
	@RequestMapping("/getPigByPigNumber.json")
	@ResponseBody
	public void getPigByPigNumber(String pigNum){
		Asserts.assertTrue(!StringUtils.isEmpty(pigNum), "没有获取到对应的数据");
		Map<String,Object> map = new HashMap<String,Object>();
		List pig = cleanPipeLineTrackService.selectPigByPigNumber(pigNum);
		if(pig.size() > 0){
			map.put("pig", pig.get(0));
		}
		AjaxSupport.sendSuccessText("", map);
	}
	
	/**
	 * 跳转到跟踪详情页面
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/getTrackDetail.html")
	public ModelAndView getTrackDetail(String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "没有获取到对应的任务数据");
		Map<String,Object> map = new HashMap<String,Object>();
//		map = cleanPipeLineTrackService.getTrackDetail(taskId,map);
		map.put("taskId", taskId);
		return forword("/pig/trackDetail", map);
	}
	/**
	 * 加载详情收发球等数据
	 * @param taskId
	 */
	@RequestMapping("/loadTrackDetail.json")
	@ResponseBody
	public void loadTrackDetail(String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "没有获取到对应的任务数据");
		Map<String,Object> map = new HashMap<String,Object>();
		map = cleanPipeLineTrackService.getTrackDetail(taskId,map);
		AjaxSupport.sendSuccessText("",map);
	}
	
	/**
	 * 加载跟踪点列表
	 * @param taskId
	 */
	@RequestMapping("/loadPointData.json")
	@ResponseBody
	public void loadPointData(String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "没有获取到对应的任务数据");
		PageJsonBean jsonBean = new PageJsonBean();
		List list = cleanPipeLineTrackService.loadTrackPoint(taskId);
		jsonBean.setList(list);
		AjaxSupport.sendSuccessText("", jsonBean);
	}
	
	/**
	 * 获取跟踪详情中跟踪点的详细信息
	 * @param code
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/getPointDetailByPointCode.json")
	@ResponseBody
	public void getPointDetailByPointCode(String pointId,String taskId){
		Asserts.assertTrue(!StringUtils.isEmpty(pointId), "没有找到跟踪点Id");
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "没有获取到任务id");
		Map<String,Object> map = new HashMap<String,Object>();
		map = cleanPipeLineTrackService.getPointDetailByPointCode(pointId,taskId);
		AjaxSupport.sendSuccessText("", map);
	}
	/**
	 * 加载地图显示信息
	 * @param taskId
	 */
	@RequestMapping("/initMapData.json")
	@ResponseBody
	public void initMapData(String taskId) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "数据异常，请刷新页面后重试");
		List list = cleanPipeLineTrackService.getTrackPointByTaskId(taskId);
		Map<String,Object> map = new HashMap<String,Object>();
		map = cleanPipeLineTrackService.getInspMonitorByTaskId(taskId,map);
		//管道上的点
		PigTask pt = cleanPipeLineManagerService.getTask(taskId);
		String reverse = cleanPipeLineTrackService.selectReverseByTaskId(taskId);
		//检测管段上的点
		
		Map<String,Object> map2 = new HashMap<String,Object>();
		map2.put("segmentId", pt.getInspSegmentId());
		map2.put("reverse", reverse);
		List<HashMap<String, Object>> data2 = cleanPipeLineManagerService.findZuoBiaoByInspSegmentId(map2);
		//改检测管段上的所有物理管段
		List<String> allPipeSegment = cleanPipeLineManagerService.findAllSegmentByInspSegmentId(pt.getInspSegmentId());
		StringBuffer json2=new StringBuffer("[");
		for (String sId : allPipeSegment) {
			if(ObjectUtil.isNotNullEmpty(sId)){
				json2.append("{").append("\"location\":").append("[");
				for (HashMap<String, Object> v2 : data2) {
					if(sId.equals(v2.get("PIPE_SEGMENT_ID").toString())){
						json2.append("\"").append(v2.get("LNG")).append(";").append(v2.get("LAT")).append("\"").append(",");
					}
				}
				json2.deleteCharAt(json2.length()-1);
				json2.append("]},");
			}
		}
		if(data2.size() >0)
		{
			json2.deleteCharAt(json2.length()-1);
		}
		json2.append("]");
		
		Map<String,Object> dataMap = new HashMap<String,Object>();
		dataMap.put("list", list);
		dataMap.put("map", map);
		dataMap.put("data2", json2.toString());
		dataMap.put("task", pt);
		AjaxSupport.sendSuccessText("", dataMap);
	}
	
	/**
	 * 详情中 预览跟踪点图片
	 * @param taskId
	 * @param pointId
	 * @return
	 */
	@RequestMapping("/getViewImg.json")
	@ResponseBody
	public void getViewImg(String taskId,String pointId){
		Asserts.assertTrue(!StringUtils.isEmpty(taskId), "数据异常，请刷新页面后重试");
		Asserts.assertTrue(!StringUtils.isEmpty(pointId), "数据异常，请刷新页面后重试");
		Map<String,Object> map = new HashMap<String,Object>();
		map = cleanPipeLineTrackService.getViewImg(taskId,pointId,map);
		AjaxSupport.sendSuccessText("", map);
	}
	
}
